import _ from "lodash";
import BW from "./bwCommon";
import urls from "./apiUrls";
import axios from "axios";
import qs from "qs";
import { Loading } from "element-ui";

/**
 * [request Ajax 公共库]
 * @param  {[String]} apiName   [api 缩写名]
 * @param  {[Object]} paramsObj [Post 参数]
 */
const request = function request(apiName, paramsObj, reqType, domStr) {
  if (_.isUndefined(urls[apiName])) {
    BW.Toast("接口地址未注册");
    return;
  }

  let sign = wVue.$store.getters.getUsrInfo
    ? wVue.$store.getters.getUsrInfo.Sign
    : "";
  let options = {
    text: "请稍候...",
    // spinner: 'el-icon-loading',
    body: true,
    background: "transparent"
  };

  if (typeof domStr === "string") {
    options.target = domStr;
    options.body = false;
  }

  if (typeof (reqType) === 'undefined') reqType = 'post'

  let postParams = reqType === 'post' ? paramsObj : ''
  let getParams = reqType === 'get' ? paramsObj : ''

  let loadingInstance = Loading.service(options);
  return new Promise((resolve, reject) => {
    axios({
      method: reqType,
      url: urls[apiName],
      data: postParams,
      params: getParams,
      // transformRequest: [function (data) {    // 转换成表单数据格式
      //   if (reqType === 'post') data = qs.stringify(data);
      //   return data;
      // }],
      responseType: 'json',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    .then(res => {
        this.$nextTick(() => {
          // 以服务的方式调用的 Loading 需要异步关闭
          loadingInstance.close();
        });
        if (!res) {
            reject({
              rspInf: '服务器 data 数据出错！'
            });
            this.$store.commit('updateLoadingStatus', false)
        }
        if (res.data) {
            if (res.data.rspCd === '00000') {
              resolve(res.data);
            } else if (res.data.rspCd === '30002' || res.data.rspCd === 'P0002') {
              BW.sureToast('登录已失效，请重新登录', () => {
                this.$store.commit('removeUsrInfo')
                this.$router.push('/login')
              })
            } else {
              BW.Toast(res.data.rspInf || '错误提示数据异常！')
              reject(res.data.rspInf);

            }
        }
      })
      .catch(error => {
        this.$nextTick(() => {
          // 以服务的方式调用的 Loading 需要异步关闭
          loadingInstance.close();
        });
        if (error.response) {
          BW.Toast("服务器出问题了！");
          reject("服务器出问题了！");
        } else {
          BW.Toast((error && error.rspInf) || "服务器出问题了！");
          reject(error.rspInf);
        }
      });
  });
};

export default request;
